import os
from docx import Document
from docx.opc.exceptions import PackageNotFoundError
# from win32com.client import Dispatch

# def convert_doc_to_docx(doc_path, docx_path):
#     word_app = Dispatch("Word.Application")
#     doc = word_app.Documents.Open(doc_path)
#     doc.SaveAs(docx_path, 12)  # 12 is the file format for docx
#     doc.Close()
#     word_app.Quit()

def count_words_in_paragraph(paragraph):
    # print(f"文字: {paragraph.text}")
    return len(paragraph.text)

def count_words_in_table(table):
    total_words = 0

    for row in table.rows:
        for cell in row.cells:
            for para in cell.paragraphs:
                total_words += count_words_in_paragraph(para)

    return total_words

def count_words_in_docx(docx_path):
    try:
        doc = Document(docx_path)
        total_words = 0

        for paragraph in doc.paragraphs:
            total_words += count_words_in_paragraph(paragraph)
            # print(f"total_words_para: {total_words}")

        for table in doc.tables:
            total_words += count_words_in_table(table)
            # print(f"total_words_table: {total_words}")

        return total_words

    except PackageNotFoundError:
        print(f"Error: Package not found. Please check if the Word document exists and is accessible.")
        return None

def get_word_count_and_filename(directory_path):
    word_counts = []
    for filename in os.listdir(directory_path):
        if filename.endswith(".docx"):
            file_path = os.path.join(directory_path, filename)
            document_word_count = count_words_in_docx(file_path)
            if document_word_count is not None:
                # print(f"文档名称: {filename}, 字数统计: {document_word_count}")
                word_counts.append((filename, document_word_count))
    return sorted(word_counts, key=lambda x: x[1])  # Sort by word count

# directory_path = '/Users/edmond/Downloads/见习报告/22计科6班企业见习'
directory_path = '/Users/edmond/Downloads/见习报告/22计科5班'
for filename, word_count in get_word_count_and_filename(directory_path):
    print(f"Document: {filename}, Word Count: {word_count}")

